from flask import Flask
from .extensions import db, login_manager


def create_app():
    app = Flask(__name__)

    # 基础配置
    configure_app(app)

    # 初始化扩展
    init_extensions(app)

    # 设置用户加载器
    setup_user_loader(app)

    # 注册蓝图（延迟导入避免循环引用）
    register_blueprints(app)

    return app


def configure_app(app):
    """应用配置"""
    app.config['SECRET_KEY'] = 'your-secret-key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@10.21.17.32/webshixun'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['USE_PLAIN_PASSWORD'] = True  # 使用明文密码
    # Redis配置
    app.config['REDIS_HOST'] = '10.21.17.32'
    app.config['REDIS_PORT'] = 6379
    app.config['REDIS_DB'] = 0
    app.config['REDIS_DECODE_RESPONSES'] = True


def init_extensions(app):
    """初始化所有扩展"""
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    
    # 初始化Redis连接
    from redis import StrictRedis
    app.redis_client = StrictRedis(
        host=app.config['REDIS_HOST'],
        port=app.config['REDIS_PORT'],
        db=app.config['REDIS_DB'],
        decode_responses=app.config['REDIS_DECODE_RESPONSES']
    )


def setup_user_loader(app):
    """设置用户加载器"""
    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))


def register_blueprints(app):
    """注册所有蓝图"""
    # 注意：这里必须放在函数内部延迟导入
    from .routes import (
        auth_bp,
        admin_bp,
        main_bp,
        annotate_bp,
        book_bp
    )

    app.register_blueprint(auth_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(main_bp)
    app.register_blueprint(annotate_bp)
    app.register_blueprint(book_bp)
